package com.scwatch.core.service.impl;

import com.scwatch.core.domain.Info;
import com.scwatch.core.domain.InfoVote;
import com.scwatch.core.repository.InfoVoteDao;
import com.scwatch.core.service.InfoVoteService;
import com.scwatch.ext.domain.Vote;
import com.scwatch.ext.service.VoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by rh005 on 2017/7/26.
 */
@Service
@Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
public class InfoVoteSeviceImpl implements InfoVoteService {
    private InfoVote findOrCreate(Info info, Vote vote) {
        InfoVote bean = dao.findOne(new InfoVote.InfoVoteId(info.getId(), vote.getId()));
        if (bean == null) {
            bean = new InfoVote(info, vote);
        }
        return bean;
    }

    @Transactional
    public void update(Info info, Integer[] voteIds) {
        // 为null不更新。要设置为空，请传空数组。
        if (voteIds == null) {
            return;
        }
        List<InfoVote> infoVotes = info.getInfoVotes();
        infoVotes.clear();
        for (Integer id : voteIds) {
            infoVotes.add(findOrCreate(info, voteService.get(id)));
        }
    }

    @Transactional
    public void deleteByVoteId(Integer voteId) {
        Vote vote = voteService.get(voteId);
        for(Info info : dao.findByInfoVoteVoteId(voteId)) {
            InfoVote infoVote = new InfoVote(info,vote);
            info.getInfoVotes().remove(infoVote);
            dao.delete(infoVote);
        }
    }

    private VoteService voteService;

    @Autowired
    public void setVoteService(VoteService voteService) {
        this.voteService = voteService;
    }

    private InfoVoteDao dao;

    @Autowired
    public void setDao(InfoVoteDao dao) {
        this.dao = dao;
    }
}
